﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DAMS.Models;
using DAMS.Service;
using DAMS.Web.Areas.Manage.Models;
using DAMS.Web.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;

namespace DAMS.Web.Areas.Manage.Controllers
{
    [Area("Manage")]
    public class CategoryController : Controller
    {
        private readonly IRepository _repo;
        private readonly IHostingEnvironment _env;
        private readonly SiteConfig _config;

        public CategoryController(IRepository repository, IHostingEnvironment env, IOptions<SiteConfig> option)
        {
            this._repo = repository;
            this._env = env;
            this._config = option.Value;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult List()
        {
            //return View(_repo.CategoryGetAll());
            CategoryCreateViewModel model = new CategoryCreateViewModel();
            Dictionary<string,string> keys= new Dictionary<string, string> { { "ID", "id" }, { "Name", "name" }, { "Type", "type" },{"ParentID","pid"}, { "Children", "children" } };
            model.TreeJson = _repo.CategoryGetTreeJson(keys);

            model.TemplatesJson = _repo.CategoryGetTemplateJson(_env.ContentRootPath);




            return View("List_Tree", model);
        }

        public IActionResult Create()
        {
            CategoryCreateViewModel model = new CategoryCreateViewModel();
            model.TreeJson = _repo.CategoryGetTreeJson();

            model.TemplatesJson = _repo.CategoryGetTemplateJson(_env.ContentRootPath);



            
            return View(model);
        }
        [HttpPost]
        public IActionResult Create([FromForm]CategoryCreateViewModel entity)
        {
            if(!ModelState.IsValid)
            {
                return View();
            }
            string[] ShowTypeList = Request.Form["ShowType"].ToString().Split(',');
            
            Category model = new Category();
            foreach (var n in ShowTypeList)
            {
                model.ShowType += int.Parse(n);
            }
            model.ParentID = entity.ParentID;
            model.Name = entity.Name;
            model.Type = entity.Type;
            model.Template = entity.Template;
            model.ArticleTemplate = entity.ArticleTemplate;
            model.Content = entity.Content;
            model.HtmlDescription = entity.HtmlDescription;
            model.HtmlKeyWord = entity.HtmlKeyWord;
            var result= _repo.CategoryCreate(model);
            if(result.Succeeded)
                return RedirectToAction("List");
            else
            {
                return Content(result.Error[0]);
            }

        }
        public IActionResult Delete(int id)
        {
            var result = _repo.CategoryDeleteByID(id);
            if (result.Succeeded)
            {
                return RedirectToAction("List");
            }
            else
            {
                return Json(new { error = 1, msg = result.SucceededMsg });
            }
        }
        public IActionResult Move(int id,int newid)
        {
            var result = _repo.CategoryMove(id, newid);
            if(result.Succeeded)
            {
                return  RedirectToAction("List");
            }
            else
            {
                return Json(new { error = 1, msg = result.SucceededMsg });
            }

        }


        public IActionResult Details(int id)
        {
            return View(_repo.CategoryGetByID(id));
        }

        public IActionResult Edit(int id)
        {
            if(id<2)
            {
                throw new Exception();
            }
            Category Entity= _repo.CategoryGetByID(id);
            CategoryEditViewModel model = new CategoryEditViewModel();
            model.ArticleTemplate = Entity.ArticleTemplate;
            model.Content = Entity.Content;
            model.Name = Entity.Name;
            IEnumerable<Category> parentList = _repo.CategoryGetParentListByID(id);
            string[] nameList= parentList.Select(x => x.Name).ToArray();
            model.ParentCategoryName = string.Join("<span style='color:red;font-weight:bold;'> › </span>", nameList);
            model.ShowType = Entity.ShowType;
            model.Template = Entity.Template;
            model.Type = Entity.Type;
            model.TemplatesJson= _repo.CategoryGetTemplateJson(_env.ContentRootPath);
            model.HtmlDescription = Entity.HtmlDescription;
            model.HtmlKeyWord = Entity.HtmlKeyWord;
            return View(model);
        }
        [HttpPost]
        public IActionResult Edit([FromForm]CategoryEditViewModel entity)
        {
            string[] ShowTypeList = Request.Form["ShowType"].ToString().Split(',');
            entity.ShowType = 0;
            foreach (var n in ShowTypeList)
            {
                entity.ShowType += int.Parse(n);
            }
            Result<Category> result= _repo.CategoryUpdate(entity.ID, entity.Name, entity.Template, entity.ArticleTemplate, entity.HtmlDescription, entity.HtmlKeyWord, entity.Content, entity.ShowType);
            if(result.Succeeded)
            {
                return RedirectToRoute(new { Action = "List" });
            }
            else
            {
                ErrorViewModel errVM = new ErrorViewModel();
                errVM.ErrorMsg = string.Join('*', result.Error);
                errVM.Redirect = Url.Action("List");
                return View("Error",errVM);
            }
            
        }
    }
}